﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Authorize.Core.Authentication;
using Authorize.Core.Cache;
using Authorize.Core.Repository;
using Authorize.Core.Repository.Implement;
using IdentityServer4;
using IdentityServer4.Models;
using IdentityServer4.Stores;

namespace Authorize.Core.Store
{
    public class ResourceStore : IResourceStore
    {
        private List<IdentityResource> _identityResources;

        public ResourceStore()
        {
            InitIdentityServer();
        }

        public Task<IEnumerable<IdentityResource>> FindIdentityResourcesByScopeAsync(IEnumerable<string> scopeNames)
        {
            var model = _identityResources.Where(x => scopeNames.Contains(x.Name));
            return Task.FromResult(model);
        }

        public Task<IEnumerable<ApiResource>> FindApiResourcesByScopeAsync(IEnumerable<string> scopeNames)
        {
            return Task.FromResult((IEnumerable<ApiResource>)ConstDataCache.ApiResourcesCache);
        }

        public Task<ApiResource> FindApiResourceAsync(string name)
        {
            return Task.FromResult(ConstDataCache.ApiResourcesCache.FirstOrDefault(x => x.Name == name));
        }

        public Task<Resources> GetAllResourcesAsync()
        {
            var result = new Resources(_identityResources, ConstDataCache.ApiResourcesCache);
            return Task.FromResult(result);
        }

        private void InitIdentityServer()
        {
            _identityResources = new List<IdentityResource>
            {
                new IdentityResources.OpenId(),
                new IdentityResource(IdentityServerConstants.StandardScopes.Profile, new []
                {
                    CustomProfileDefault.UserName,
                    CustomProfileDefault.NickName,
                    CustomProfileDefault.Phone,
                    CustomProfileDefault.Email,
                    CustomProfileDefault.OpenId,
                    CustomProfileDefault.DeviceId,
                    CustomProfileDefault.Sex,
                    CustomProfileDefault.AvartarUrl,
                    CustomProfileDefault.CreateDate,
                    CustomProfileDefault.LastLoginDate
                })
            };
        }
    }
}
